import { defineStore } from "pinia";
import common_util from "@/util/common_util.js";
import { toRaw } from "vue";
import { ElMessage } from "element-plus";
import qs from "qs";

export const usePlanStores = defineStore("plan", {
  state: () => ({
    plans: [], // 学生可见的计划列表
    planingNow: {
      title: "111",
      content: "111",
      category: "1",
      startDate: "",
      endDate: "",
    },
    editNow: {
      id: "",
      title: "",
      content: "",
      category: "",
      startDate: "",
      endDate: "",
    },
    loading: false,
    // 分页相关状态
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filter: {
      category: null,
      dateRange: [],
      status: null
    }
  }),
  
  getters: {
    // 获取日历事件数据
    calendarEvents: (state) => {
      const events = {};
      state.plans.forEach(plan => {
        const startDate = new Date(plan.plan.startDate);
        const endDate = new Date(plan.plan.endDate);
        for (
          let d = new Date(startDate);
          d <= endDate;
          d = new Date(d.getTime() + 24 * 60 * 60 * 1000)
        ) {
          const dateStr = d.toISOString().split('T')[0];
          if (!events[dateStr]) events[dateStr] = [];
          events[dateStr].push({
            title: plan.plan.title,
            class: plan.plan.category === 0 ? 'bg-success' : 'bg-warning',
            planId: plan.plan.id,
            status: plan.status
          });
        }
      });
      return events;
    },
    
    // 获取即将到来的培训（按时间排序，只显示未完成的）
    upcomingTrainings: (state) => {
      const now = new Date();
      const upcoming = [];
      
      state.plans.forEach(plan => {
        if (plan.status === 0) { // 只显示未完成的计划
          const startDate = new Date(plan.plan.startDate);
          const endDate = new Date(plan.plan.endDate);
          
          // 如果计划还没开始或正在进行中
          if (endDate >= now) {
            const daysDiff = Math.ceil((startDate - now) / (1000 * 60 * 60 * 24));
            let remaining = '';
            
            if (daysDiff < 0) {
              remaining = '进行中';
            } else if (daysDiff === 0) {
              remaining = '今天';
            } else if (daysDiff === 1) {
              remaining = '明天';
            } else {
              remaining = `${daysDiff}天后`;
            }
            
            upcoming.push({
              title: plan.plan.title,
              type: `${plan.plan.category === 0 ? '课程安排' : '考核节点'}`,
              remaining: remaining,
              date: startDate.toISOString().split('T')[0],
              planId: plan.plan.id,
              status: plan.status,
              category: plan.plan.category,
              startDate: startDate,
              endDate: endDate
            });
          }
        }
      });
      
      // 按开始时间排序
      return upcoming.sort((a, b) => new Date(a.date) - new Date(b.date)).slice(0, 5);
    },
    
    // 计算学习进度
    learningProgress: (state) => {
      if (state.plans.length === 0) return 0;
      const completed = state.plans.filter(plan => plan.status === 1).length;
      return Math.round((completed / state.plans.length) * 100);
    },

    // 根据筛选条件过滤计划
    filteredPlans: (state) => {
      let plans = state.plans;
      
      if (state.filter.category !== null) {
        plans = plans.filter(plan => plan.plan.category === state.filter.category);
      }
      
      if (state.filter.status !== null) {
        plans = plans.filter(plan => plan.status === state.filter.status);
      }
      
      if (state.filter.dateRange && state.filter.dateRange.length === 2) {
        const [startDate, endDate] = state.filter.dateRange;
        plans = plans.filter(plan => {
          const planStart = new Date(plan.plan.startDate);
          const planEnd = new Date(plan.plan.endDate);
          const filterStart = new Date(startDate);
          const filterEnd = new Date(endDate);
          
          return planStart <= filterEnd && planEnd >= filterStart;
        });
      }
      
      return plans;
    }
  },
  
  actions: {
    cleanPlaningNow() {
      this.planingNow = {
        title: "",
        content: "",
        category: "",
        startDate: "",
        endDate: "",
      };
    },
    
    // 获取学生可见的计划列表
    async getStudentPlans() {
      this.loading = true;
      try {
        await common_util.get("/api/plans/by-student", {}, (data) => {
          this.plans = data || [];
        });
      } catch (error) {
        console.error("获取计划列表失败:", error);
        ElMessage.error("获取计划列表失败");
      } finally {
        this.loading = false;
      }
    },
    
    // 分页获取学生计划
    async getStudentPlansPage(pageNo = 1, pageSize = 10) {
      this.loading = true;
      try {
        const result = await new Promise((resolve, reject) => {
          common_util.get("/api/plans/by-student/page", {
            pageNo,
            pageSize
          }, (data, total) => {
            this.plans = data || [];
            this.pagination.currentPage = pageNo;
            this.pagination.pageSize = pageSize;
            this.pagination.total = total || 0;
            resolve({ data, total });
          });
        });
        return result;
      } catch (error) {
        console.error("获取计划列表失败:", error);
        ElMessage.error("获取计划列表失败");
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 完成计划
    async finishPlan(planId) {
      try {
        await common_util.put(`/api/plans/${planId}/finish`, {}, {}, (data) => {
          ElMessage.success("计划完成！");
          // 重新获取计划列表以更新状态
          this.getStudentPlans();
        });
      } catch (error) {
        console.error("完成计划失败:", error);
        ElMessage.error("完成计划失败");
        throw error;
      }
    },
    
    // 获取待完成的计划（用于提醒）
    async getPendingPlans() {
      try {
        return await new Promise((resolve, reject) => {
          common_util.get("/api/plans/pending", {}, (data) => {
            resolve(data || []);
          });
        });
      } catch (error) {
        console.error("获取待完成计划失败:", error);
        return [];
      }
    },
    
    // 创建计划（老师/管理员功能）
    async createPlan(createdBy, courseIds = []) {
      this.planingNow.createdBy = createdBy;
      try {
        await common_util.post(
          "/api/plans/upload",
          toRaw(this.planingNow),
          { courseIds },
          (data) => {
            this.cleanPlaningNow();
            ElMessage.success("创建计划成功");
            return data;
          },
        );
      } catch (error) {
        console.error("创建计划失败:", error);
        ElMessage.error("创建计划失败");
        throw error;
      }
    },
    
    // 获取所有计划（管理员功能）
    // async getAllPlans() {
    //   this.loading = true;
    //   try {
    //     await common_util.get("/api/plans", {}, (data) => {
    //       this.plans = data || [];
    //     });
    //   } catch (error) {
    //     console.error("获取所有计划失败:", error);
    //     ElMessage.error("获取所有计划失败");
    //   } finally {
    //     this.loading = false;
    //   }
    // },
    async getAllPlans() {
      this.loading = true;
      // 返回一个Promise，以便调用方可以拿到数据
      return new Promise((resolve, reject) => {
        common_util.get("/api/plans", {}, (data) => {
          this.plans = data || []; // 保持对state的更新
          this.loading = false;
          resolve(data || []); // 成功时，将数据传递出去
        }, (error) => {
          console.error("获取所有计划失败:", error);
          ElMessage.error("获取所有计划失败");
          this.loading = false;
          reject(error); // 失败时，抛出错误
        });
      });
    },
    
    // 分页获取所有计划（管理员功能）
    async getAllPlansPage(pageNo = 1, pageSize = 10) {
      this.loading = true;
      try {
        const result = await new Promise((resolve, reject) => {
          common_util.get("/api/plans/page", {
            pageNo,
            pageSize
          }, (data, total) => {
            this.plans = data || [];
            this.pagination.currentPage = pageNo;
            this.pagination.pageSize = pageSize;
            this.pagination.total = total || 0;
            resolve({ data, total });
          });
        });
        return result;
      } catch (error) {
        console.error("获取计划列表失败:", error);
        ElMessage.error("获取计划列表失败");
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 获取老师发布的计划
    async getTeacherPlans() {
      this.loading = true;
      try {
        await common_util.get("/api/plans/by-teacher", {}, (data) => {
          this.plans = data || [];
        });
      } catch (error) {
        console.error("获取老师计划失败:", error);
        ElMessage.error("获取老师计划失败");
      } finally {
        this.loading = false;
      }
    },
    
    // 分页获取老师发布的计划
    async getTeacherPlansPage(pageNo = 1, pageSize = 10) {
      this.loading = true;
      try {
        const result = await new Promise((resolve, reject) => {
          common_util.get("/api/plans/by-teacher/page", {
            pageNo,
            pageSize
          }, (data, total) => {
            this.plans = data || [];
            this.pagination.currentPage = pageNo;
            this.pagination.pageSize = pageSize;
            this.pagination.total = total || 0;
            resolve({ data, total });
          });
        });
        return result;
      } catch (error) {
        console.error("获取老师计划失败:", error);
        ElMessage.error("获取老师计划失败");
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取指定计划详情
    async getPlanById(planId) {
      try {
        return await new Promise((resolve, reject) => {
          common_util.get(`/api/plans/${planId}`, {}, (data) => {
            resolve(data);
          });
        });
      } catch (error) {
        console.error("获取计划详情失败:", error);
        ElMessage.error("获取计划详情失败");
        throw error;
      }
    },

    // 手动触发学习提醒（管理员/老师可用）
    async triggerReminder() {
      try {
        await common_util.post("/api/plans/trigger-reminder", {}, {}, (data) => {
          ElMessage.success("提醒发送完成");
        });
      } catch (error) {
        console.error("触发提醒失败:", error);
        ElMessage.error("触发提醒失败");
        throw error;
      }
    },

    // 设置筛选条件
    setFilter(filter) {
      this.filter = { ...this.filter, ...filter };
    },

    // 清除筛选条件
    clearFilter() {
      this.filter = {
        category: null,
        dateRange: [],
        status: null
      };
    },

    // 根据用户角色获取计划
    async getPlansByRole(role, pageNo = 1, pageSize = 10) {
      switch (role) {
        case 'student':
          return await this.getStudentPlansPage(pageNo, pageSize);
        case 'teacher':
          return await this.getTeacherPlansPage(pageNo, pageSize);
        case 'admin':
          return await this.getAllPlansPage(pageNo, pageSize);
        default:
          throw new Error('未知的用户角色');
      }
    },

    // 刷新数据
    async refreshData(role = 'student') {
      try {
        await this.getPlansByRole(role, this.pagination.currentPage, this.pagination.pageSize);
        ElMessage.success("数据刷新成功");
      } catch (error) {
        console.error("刷新数据失败:", error);
        ElMessage.error("刷新数据失败");
      }
    },

    // 处理分页变化
    async handlePageChange(pageNo, pageSize, role = 'student') {
      try {
        await this.getPlansByRole(role, pageNo, pageSize);
      } catch (error) {
        console.error("分页获取数据失败:", error);
      }
    },

    // 应用筛选并重新获取数据
    async applyFilter(role = 'student') {
      try {
        // 重置到第一页
        this.pagination.currentPage = 1;
        await this.getPlansByRole(role, 1, this.pagination.pageSize);
        ElMessage.success("筛选条件已应用");
      } catch (error) {
        console.error("应用筛选失败:", error);
        ElMessage.error("应用筛选失败");
      }
    },

    // 获取我的计划（老师功能）
    getMyPlanning(teacherId) {
      this.plans = [];
      common_util.get("/api/plans/by-teacher", { teacherId }, (data) => {
        this.plans = data;
      });
    },

    // 更新计划
    updatePlan(createdBy, courseIds) {
      console.log("updatePlan");
      this.planingNow.createdBy = createdBy;
      // 使用qs序列化courseIds数组
      const courseIdsString = qs.stringify(
        { courseIds },
        { arrayFormat: "repeat" },
      );
      console.log("courseIdsString", courseIdsString);
      // 将 courseIdsString 放到 params 对象中
      const params = { courseIds: courseIdsString };
      common_util.post(
        "/api/plans/upload",
        { ...toRaw(this.planingNow) },
        params,
        (data) => {
          this.cleanPlaningNow();
          this.getAllPlanning();
          ElMessage.success("创建计划成功");
        },
      );
    },
  },
});
